<template>
  <div>
    <video
      ref="videoElement"
      controls
      muted
      autoplay
      style="width: 100%; max-width: 800px"
    ></video>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import flvjs from "flv.js";

const videoElement = ref(null);
const flvPlayer = ref(null);
const error = ref(null);

onMounted(() => {
  if (flvjs.isSupported()) {
    flvPlayer.value = flvjs.createPlayer({
      type: "flv",
      url: "",
      isLive: true, // 直播流需开启
      hasAudio: true, // 根据实际需求调整
      hasVideo: true,
    });

    flvPlayer.value.attachMediaElement(videoElement.value);
    flvPlayer.value.load();
    flvPlayer.value.play().catch((e) => {
      error.value = `播放失败: ${e.message}`;
    });
  } else {
    error.value = "当前浏览器不支持 flv.js";
  }
});

onUnmounted(() => {
  if (flvPlayer.value) {
    flvPlayer.value.pause();
    flvPlayer.value.unload();
    flvPlayer.value.destroy();
  }
});
</script>

<style scoped>
.error {
  color: red;
  margin-top: 10px;
}
</style>
